package cn.yeziji.common;

import org.apache.poi.ss.formula.functions.T;

import java.util.List;
import java.util.Objects;

/**
 * 自定义 list 分页
 *
 * @author gzkemays
 * @date 2021/4/17 21:35
 */
public class GPageUtils {
  /**
   * 构造分页
   *
   * @param list 需要进行分页的集合列表
   * @param pageNum 页码
   * @param pageSize 每页多少条数据
   * @return
   */
  public static List<T> create(List<T> list, Integer pageNum, Integer pageSize) {
    if (Objects.isNull(list) || list.isEmpty()) {
      return null;
    }
    if (Objects.isNull(pageNum)) {
      pageNum = 1;
    }
    if (Objects.isNull(pageSize)) {
      pageSize = 10;
    }
    Integer count = list.size(); // 记录总数
    int pageCount; // 页数
    if (count % pageSize == 0) {
      pageCount = count / pageSize;
    } else {
      pageCount = count / pageSize + 1;
    }

    int fromIndex; // 开始索引
    int toIndex; // 结束索引

    if (pageNum != pageCount) {
      fromIndex = (pageNum - 1) * pageSize;
      toIndex = fromIndex + pageSize;
    } else {
      fromIndex = (pageNum - 1) * pageSize;
      toIndex = count;
    }
    return list.subList(fromIndex, toIndex);
  }
}
